import turbogears as tg
from turbogears import controllers, expose, flash, validators, redirect
from turbogears.widgets import WidgetsList, TableForm, TextField, HiddenField
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.publisher")

from cherrypy import session

class PublisherFormList(WidgetsList):
    name = TextField(label=_("Name"),
                     validator=validators.NotEmpty(),
                     attrs={"size":"70"})
    webPage = TextField(label=_("Home Page"),
                        attrs={"size":"70"})
    retInfo = HiddenField()


publisherForm = TableForm(
    fields = PublisherFormList(),
    action = "save",
    submit_text = _("Submit")
    )


class PublisherCadaster(controllers.Controller):
    @expose()
    def default(self, *k, **kw):
        redirect(tg.url("/"))

    @expose(template="bookloantracker.templates.authorcadaster")
    def index(self, name=None, ret=None):
        values = {}
        if name:
            values["name"] = name
        if ret:
            values["retInfo"] = ret
        return dict(form = publisherForm,
                    values = values)

    @expose()
    def save(self, name, webPage=None, 
             retInfo=None):
        redirectTarget = "index"
        if retInfo:
            redirectTarget = "/"+"/".join(retInfo.split("."))
        log.debug("redirectTarget = %s" % redirectTarget)
        publisherList = Publisher.selectBy(name=name)
        if publisherList.count():
            flash(_("Publisher alredy registered"))
            redirect(redirectTarget)
        publisher = Publisher(name = name,
                              webPage = webPage)
        flash(_("Publisher registered"))
        redirect(redirectTarget)
        return {}
